package com.jlyx.scwechatgoods.common;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author sesshomaru
 * @date 2019/12/3 22:33
 */
@Component
public class RestTemplateHelper {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * get 请求
     * @param url
     * @return
     */
    public String get(String url){
       return restTemplate.getForObject(url,String.class);
    }

    public String getForData(String url, MultiValueMap<String, Object> param){
       return restTemplate.getForObject(url,String.class,param);
    }

    /**
     * 采用post请求，数据格式为 application/json，并且返回结果是JSON string
     * @param url
     * @param json
     * @return
     */
    public String postForJson(String url, String json){
        //设置Http Header
        HttpHeaders headers = new HttpHeaders();
        //设置请求媒体数据类型
        headers.setContentType(MediaType.APPLICATION_JSON);
        //设置返回媒体数据类型
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(json, headers);
        return restTemplate.postForObject(url, formEntity, String.class);
    }

    /**
     * 采用post请求，数据格式为 application/x-www-form-urlencoded，并且返回结果是JSON string
     * @param url
     * @param param
     * @return
     */
    public String postInvocation(String url,  MultiValueMap<String, Object> param){
        //设置Http Header
        HttpHeaders headers = new HttpHeaders();
        //设置请求媒体数据类型
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //设置返回媒体数据类型
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        return restTemplate.postForObject(url, httpEntity,String.class);
    }
}
